#!/usr/bin/env python
"""


   Syntax:

      ::marco::
         marco scripts
      ::end-marco::


"""

import os
import re
import tempfile
from subprocess import Popen, PIPE
from zlib import adler32
import logging
import markdown
from markdown.util import etree


logger = logging.getLogger('MARKDOWN')
none='no_rwo'
color_table=dict(no_rwo="background-color:yellowgreen;color:black;",
RW="background-color:yellow;color:black;",
RWO="background-color:red;color:white;",
WO="background-color:rgb(0,255,255);color:black;",W="background-color:blue;color:black;")
def _table_line(cell_bits,line_bits,arg):
    assert(line_bits%cell_bits==0)
    s=0
    line_limit=s+line_bits
    line=[('%03x' % (s),1,None,None),]
    for name,bits,rwo in arg:
        while s+bits > line_limit:
            if s % line_bits == 0 and bits % line_bits == 0:
                line.append((name,int((line_limit-s)/cell_bits),rwo,int(bits/line_bits)))
                yield line
                for i in range(1,int(bits/line_bits)):
                    s+=line_bits
                    line=[('%03x' % (s),1,None,None),]
                    yield line
                s+=line_bits
                line=[('%03x' % (s),1,None,None),]
                line_limit=s+line_bits
                bits=0
                continue
            line.append((name,int((line_limit-s)/cell_bits),rwo,None))
            yield line
            bits-=(line_limit-s)
            s=line_limit
            line=[('%03x' % (s),1,None,None),]
            line_limit+=line_bits
        if bits == 0:
            continue
        if s+bits < line_limit:
            line.append((name,int(bits/cell_bits),rwo,None))
            s+=bits
        elif s+bits == line_limit:
            line.append((name,int(bits/cell_bits),rwo,None))
            yield line
            s+=bits
            line=[('%03x' % (s),1,None,None),]
            line_limit+=line_bits
def create_efuse_table(table,arg=[],cell_bits=8,line_bits=128):
    assert(isinstance(table,etree.Element) and table.tag == 'table')
    table.attrib['class']='gridtable'
    table.attrib['width']='90%'
    thead=etree.SubElement(table,'thead')
    th=etree.SubElement(thead,'th')
    th.attrib['width']='10%'

    for i in range(0,line_bits,cell_bits):
        th=etree.SubElement(thead,'th',{'width':'5%'})
        th.text='%02x' %i
    tbody=etree.SubElement(table,'tbody')
    rows=list(_table_line(cell_bits,line_bits,arg))
    for row in rows:
        tr=etree.SubElement(tbody,'tr')
        for name,cells,color,rowspan in row:
            td=etree.SubElement(tr,'td')
            td.text=name
            td.attrib['colspan']=str(cells)
            if color is not None:
                td.attrib['style']=color_table[color]
            if rowspan is not None:
                td.attrib['rowspan']=str(rowspan)
    return table

# For details see https://pythonhosted.org/Markdown/extensions/api.html#blockparser
class MarcoBlockProcessor(markdown.blockprocessors.BlockProcessor):
    # Regular expression inspired by the codehilite Markdown plugin
    RE = re.compile(r'::macro::')
    # Regular expression for identify end of UML script
    RE_END = re.compile(r'::end-macro::\s*$')

    def test(self, parent, block):
        #~ print(self.RE.search)
        return self.RE.search(block)

    def run(self, parent, blocks):
        block = blocks.pop(0)
        text = block
        print(text)
        # Parse configuration params
        m = self.RE.search(block)

        # Read blocks until end marker found
        while blocks and not self.RE_END.search(block):
            block = blocks.pop(0)
            text += '\n' + block
        else:
            if not blocks:
                raise RuntimeError("UML block not closed")
        text = re.sub(self.RE, "", text)
        text=re.sub(self.RE_END, "", text)
        try:
            # Create image tag and append to the document
            arg=eval(text)
        except Exception as e:
            element=etree.SubElement(parent, "pre")
            element.text=str(e) + '\n' + text
        else:
            element=etree.SubElement(parent, "table")
            create_efuse_table(element,**arg)

            #~ raise
        #~ print(text)

# For details see https://pythonhosted.org/Markdown/extensions/api.html#extendmarkdown
class MarcoMarkdownExtension(markdown.Extension):
    # For details see https://pythonhosted.org/Markdown/extensions/api.html#configsettings
    def __init__(self, *args, **kwargs):


        super(MarcoMarkdownExtension, self).__init__(*args, **kwargs)

    def extendMarkdown(self, md, md_globals):
        blockprocessor = MarcoBlockProcessor(md.parser)
        blockprocessor.config = self.getConfigs()
        md.parser.blockprocessors.add('macro', blockprocessor, '>code')


def makeExtension(*args, **kwargs):
    print('rrr')
    return MarcoMarkdownExtension(*args, **kwargs)
